﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WXJH;


namespace WXJHToolBox
{
    public class WinCCArchiveHelper
    {        
        /// <summary>
        /// 获取归档变量时间段的数据，并存到DataTable中
        /// </summary>
        /// <param name="conStr">连接字符串</param>
        /// <param name="index">变量编号</param>
        /// <param name="tfrom">开始时间Local</param>
        /// <param name="tto">结束时间Local</param>
        /// <param name="colName">Table中显示的数据列名称</param>
        /// <param name="sampletime">采样时间</param>
        /// <returns></returns>
        public static DataTable GetArchiveData(int index, string tfrom, string tto, string colName, string sampletime)
        {
            string timeStep = ",'TIMESTEP=" + sampletime + ",1'";
            string sql = "TAG:R," + index + ",'" + Common.GetWinCCDateTime(tfrom) + "','" + Common.GetWinCCDateTime(tto) + "'" + timeStep;
            DataTable dt = OleDbHelper.ExecuteDataTable( sql);
            dt.Columns["RealValue"].ColumnName = colName;
            return dt.DefaultView.ToTable(false, new string[] { "Timestamp", colName });
        }

        public static List<DataTable> GetArchiveDataList(List<int> indexArr, string tfrom, string tto, List<string> colName, string sampletime)
        {
            List<DataTable> dtList = new List<DataTable>();
            string timeStep = ",'TIMESTEP=" + sampletime + ",1'";
            List<int> count = new List<int>();
            for (int i = 0;i<indexArr.Count;i++)
            {
                string sql = "TAG:R," + indexArr[i] + ",'" + Common.GetWinCCDateTime(tfrom) + "','" + Common.GetWinCCDateTime(tto) + "'" + timeStep;
                try
                {
                    DataTable dt = OleDbHelper.ExecuteDataTable(sql);
                    dt.Columns["RealValue"].ColumnName = colName[i];
                    dt.DefaultView.ToTable(false, new string[] { "Timestamp", colName[i] });
                    count.Add(dt.Rows.Count);
                    dtList.Add(dt);
                }
                catch 
                {
                    return null;
                }
            }

           if( count.Max()!=count.Min() || count.Min()<=0)
            {
                Logs.Info("获取的数据长度不一致");
                return null;
            };
            return dtList;
        }

        /// <summary>
        /// 根据变量列表创建DataTable
        /// </summary>
        /// <param name="colNames">变量名称列表</param>
        /// <returns></returns>
        public static DataTable CreateDataTable(List<string> colNames)
        {
            if (colNames.Count <= 0)
            {
                return null;
            }
            else
            {
                DataTable dtReturn = new DataTable();
                for (int i = 0; i < colNames.Count; i++)
                {
                    DataColumn newColumn = new DataColumn(colNames[i], System.Type.GetType("System.String"))
                    {
                        Caption = colNames[i],//表头
                        DefaultValue = string.Empty
                    };
                    dtReturn.Columns.Add(newColumn);
                };
                return dtReturn;
            }
        }

        /// <summary>
        /// 只针对归档数据库数据的合并
        /// </summary>
        /// <param name="tables">归档数据查询出来的数据</param>
        /// <param name="colNames"></param>
        /// <returns></returns>
        public static DataTable MergeDataTable(List<DataTable> tables)
        {
            if (tables.Count <= 0) { return null; }
            List<string> colNames = new List<string>
            {
                "Timestamp"
            };
            foreach (DataTable table in tables)
            {

                colNames.Add(table.Columns[1].ColumnName.ToString());
            }
            DataTable dt = CreateDataTable(colNames);

            for (int rowcount = 0; rowcount < tables[0].Rows.Count; rowcount++)  //创建一行
            {
                DataRow dr = dt.NewRow();
                dr[0] = tables[0].Rows[rowcount][0];//归档数据的时间
                for (int tableIndex = 0; tableIndex < tables.Count; tableIndex++)//表的数量
                {
                    dr[tableIndex + 1] = tables[tableIndex].Rows[rowcount][1];//每个表当中的数据列，组成一行添加到新表中
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
        public static DataSet SplitDataTable(DataTable srcTable, List<string> tablesName)
        {
            int tablesNum = tablesName.Count;
            if (tablesNum <= 0) return null;
            if (srcTable == null || srcTable.Rows.Count <= 0 || srcTable.Rows.Count % tablesNum != 0) return null;
            //归档数据查出来肯定都是能整除的          
            int rowsNum = srcTable.Rows.Count / tablesNum;
            DataSet ds = new DataSet();
            DataTable[] tableSlice = new DataTable[tablesNum];
            for (int i = 0; i < tablesNum; i++)
            {
                tableSlice[i] = new DataTable();
                foreach (DataColumn dc in srcTable.Columns)
                {
                    tableSlice[i].Columns.Add(dc.ColumnName, dc.DataType);
                }
            }

            for (int i = 0; i < tablesNum; i++)
            {
                for (int j = i * rowsNum; j < ((i + 1) * rowsNum); j++)
                {
                    tableSlice[i].ImportRow(srcTable.Rows[j]);
                }
            }

            for (int i = 0; i < tablesNum; i++)
            {
                tableSlice[i].TableName = tablesName[i];
                ds.Tables.Add(tableSlice[i]);
            }
            return ds;
        }


        

        public static Dictionary<DateTime, string> GetArchiveTagData(
            string ArchiveTagName, DateTime LocalBeginDT, DateTime LocalEndDT, string timeSpace = "3600", 
            Common.DtyTagType dataType = Common.DtyTagType.Float, Common.DtyDigs dig = Common.DtyDigs.Two, 
            Common.DtySimple simple = Common.DtySimple.First, bool IsNewer = true, bool BatchMode = false, bool IsFirstTag = false)
        {
            string winCCDateTime = Common.GetWinCCDateTime(LocalBeginDT);
            string winCCDateTime2 = Common.GetWinCCDateTime(LocalEndDT);
            int num = 3;
            if (IsNewer)
            {
                num = 2;
            }
            OleDbCommand oleDbCommand = new OleDbCommand();
            oleDbCommand.Connection = OleDbHelper.ConnToWinCCDB();  
            if (oleDbCommand == null)
            {
                Logs.Info("连接至WinCC数据库失败！");
                return null;
            }
            try
            {
                oleDbCommand.CommandText = "TAG:R,('" + ArchiveTagName + "'),'" + winCCDateTime + "','" + winCCDateTime2 + "'," + $"'TIMESTEP={timeSpace},{(int)simple}'";
                if (BatchMode)
                {
                    oleDbCommand.CommandText = "TAG:R,('" + ArchiveTagName + "'),'" + winCCDateTime + "','" + winCCDateTime2 + "','TIMESTEP=0,0'";
                }
                if (dataType == Common.DtyTagType.String)
                {
                    oleDbCommand.CommandText = "TAG_EX:R,('" + ArchiveTagName + "'),'" + winCCDateTime + "','" + winCCDateTime2 + "','TIMESTEP=0,0'";
                }
                OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader();
                Dictionary<DateTime, string> dictionary = new Dictionary<DateTime, string>();
                while (oleDbDataReader.Read())
                {
                    if (dataType == Common.DtyTagType.Float)
                    {
                        dictionary.Add(Common.GetLocalDT(oleDbDataReader.GetValue(1)), Math.Round(Convert.ToDouble(oleDbDataReader.GetValue(num)), (int)dig).ToString($"F{(int)dig}"));
                    }
                    else if (dataType == Common.DtyTagType.Bool && IsFirstTag)
                    {
                        if (Convert.ToBoolean(oleDbDataReader.GetValue(num)))
                        {
                            dictionary.Add(Common.GetLocalDT(oleDbDataReader.GetValue(1)), oleDbDataReader.GetValue(num).ToString());
                        }
                    }
                    else
                    {
                        dictionary.Add(Common.GetLocalDT(oleDbDataReader.GetValue(1)), oleDbDataReader.GetValue(num + 1).ToString());
                    }
                }
                oleDbDataReader.Close();
                oleDbCommand.Dispose();
                return dictionary;
            }
            catch(Exception ex)
            {
                Logs.Info("GetArchiveTagData:" + ex.Message);
                return null;
            }
        }
    }
}








